package com.glamour.hlcity.dal.dao.impl;

import com.glamour.hlcity.common.condition.QueryCondition;
import com.glamour.hlcity.common.model.Entity;
import com.glamour.hlcity.common.util.ListUtil;
import com.glamour.hlcity.dal.dao.GenricDao;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import java.util.Date;
import java.util.List;

public class SqlMapDaoHelper<T extends Entity> extends SqlMapClientDaoSupport
		implements GenricDao<T> {
	private String persistentClassShortName;

	public SqlMapDaoHelper(String persistentClassShortName) {
		this.persistentClassShortName = persistentClassShortName;
	}

	public SqlMapDaoHelper(Class<T> clazz) {
		this(clazz.getSimpleName());
	}

	public Integer countByCondition(QueryCondition condition) {
		return (Integer) getSqlMapClientTemplate().queryForObject(
				getQualifiedStatementName("countByCondition"),
				condition.asMap());
	}

	public T insert(T entity) {
		entity.setGmtCreate(new Date());
		entity.setGmtModified(new Date());

		Long id = (Long) getSqlMapClientTemplate().insert(
				getQualifiedStatementName("insert"), entity);
		entity.setId(id);

		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<T> selectByConditon(QueryCondition condition) {
		return getSqlMapClientTemplate().queryForList(
				getQualifiedStatementName("selectByCondition"),
				condition.asMap());
	}

	public Integer update(T entity) {
		return getSqlMapClientTemplate().update(
				getQualifiedStatementName("update"), entity);
	}

	public Integer updateByCondition(QueryCondition condition) {
		return getSqlMapClientTemplate().update(
				getQualifiedStatementName("updateByCondition"),
				condition.asMap());
	}

	protected String getQualifiedStatementName(String statementName) {
		return new StringBuilder(persistentClassShortName).append(".").append(
				statementName).toString();
	}

	public T getById(Long id) {
		QueryCondition condition = new QueryCondition();
		condition.add("id", id);

		List<T> list = selectByConditon(condition);

		return ListUtil.first(list);
	}

	public Integer deleteById(Long id) {
		QueryCondition condition = new QueryCondition();
		condition.add("id", id);
		condition.add("isDelete", "y");
		return updateByCondition(condition);
	}
}
